package cn.manyufun.myf.ui.comics.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import cn.manyufun.myf.R;
import cn.manyufun.myf.api.Api;
import cn.manyufun.myf.api.HostType;
import cn.manyufun.myf.app.AppConstant;
import cn.manyufun.myf.bean.BaseBean;
import cn.manyufun.myf.bean.ComicsDetailBean;
import cn.manyufun.myf.bean.ReplyBean;
import cn.manyufun.myf.common.base.BaseActivity;
import cn.manyufun.myf.common.baserx.RxSchedulers;
import cn.manyufun.myf.common.baserx.RxSubscriber;
import cn.manyufun.myf.common.commonutils.APIUtils;
import cn.manyufun.myf.common.commonutils.DisplayUtil;
import cn.manyufun.myf.common.commonutils.ImageLoaderUtils;
import cn.manyufun.myf.common.commonutils.ToastUtil;
import cn.manyufun.myf.common.commonwidget.NormalTitleBar;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class EditCommentActivity extends BaseActivity {
    public static final String INTENT_KEY = "COMICS";
    public static final String IS_FROM_RATING = "RATING";
    public static final String REPLY_INFO = "REPLY";
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.iv_comics_photo)
    ImageView mIvComicsPhoto;
    @BindView(R.id.tv_comics_title)
    TextView mTvComicsTitle;
    @BindView(R.id.rb_score)
    RatingBar mRbScore;
    @BindView(R.id.tv_score)
    TextView mTvScore;
    @BindView(R.id.ll_type)
    LinearLayout mLLType;
    @BindView(R.id.tv_follow_num)
    TextView mTvFollowNum;
    @BindView(R.id.tv_comment_num)
    TextView mTvCommonNum;
    @BindView(R.id.tv_view_num)
    TextView mTvViewNum;
    @BindView(R.id.rb_score_edit)
    RatingBar mRbEdit;
    @BindView(R.id.et_comment)
    EditText mEdComment;
    @BindView(R.id.tv_score_edit)
    TextView mTvScoreEdit;

    private ComicsDetailBean mBean;
    private ReplyBean mReply;

    public static void startAction(Context context, Bundle bundle) {
        Intent intent = new Intent(context, EditCommentActivity.class);
        if (bundle != null)
            intent.putExtras(bundle);

        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_edit_comment;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        Intent intent = getIntent();
        mBean = intent.getParcelableExtra(INTENT_KEY);
        mReply = intent.getParcelableExtra(REPLY_INFO);

        ntb.setTitleText("评分/短评");
        ntb.setRightTitle("确定");
        ntb.setRightTitleVisibility(true);
        ntb.setOnBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        ntb.setOnRightTextListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String content = mEdComment.getText().toString();
                float score = mRbEdit.getRating();
                if (TextUtils.isEmpty(content) && score == 0) {
                    ToastUtil.showLong("评论内容和分数请至少输入一个。。");
                    return;
                }
                Api.getDefault(HostType.manyufun).setCommentReply(getCommonRpleyRequestBody())
                        .compose(RxSchedulers.<BaseBean>io_main())
                        .subscribe(new RxSubscriber<BaseBean>(EditCommentActivity.this, false) {
                            @Override
                            public void onStart() {
                                super.onStart();
                            }

                            @Override
                            protected void _onNext(BaseBean posterBean) {
                                if (posterBean.getSuccess().equals("1")) {
                                    ToastUtil.show("提交成功", 3);
                                    mRxManager.post(AppConstant.COMICS_EDIT_COMMENT_OR_ARTICLE, null);
                                    finish();
                                } else {
                                    ToastUtil.show(posterBean.getErrorMsg(), 3);
                                }
                            }

                            @Override
                            protected void _onError(String message) {

                            }
                        });

            }
        });

        mTvComicsTitle.setText(mBean.getTitle());
        mTvScore.setText(mBean.getScore() + "");
        mRbScore.setRating(mBean.getScore());
        mTvCommonNum.setText(mBean.getCommentNum() + "");
        mTvFollowNum.setText(mBean.getFollowNum() + "");
        mTvViewNum.setText(mBean.getViewNum() + "");
        ImageLoaderUtils.displayRoundCorners(this, mIvComicsPhoto, mBean.getCoverImages().get(0), 10);

        List<String> type = mBean.getComicType();
        mLLType.removeAllViews();
        for (String t : type) {
            TextView tv = (TextView) getLayoutInflater().inflate(R.layout.type_text, null);
            LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            param.setMarginEnd(DisplayUtil.dip2px(5f));
            tv.setLayoutParams(param);
            tv.setText(t);
            mLLType.addView(tv);
        }

        if (mReply != null) {
            mRbEdit.setRating(mReply.Score);
            mEdComment.setText(mReply.Content);
            mTvScoreEdit.setText("点击修改漫画评分");
        }
    }

    private RequestBody getCommonRpleyRequestBody() {
        JSONObject root = new JSONObject();
        JSONObject head = APIUtils.getHeadParamter();
        try {
            root.put("Head", head);
            root.put("ComicId", mBean.getComicId());
            root.put("ReplyId", mReply == null ? 0 : mReply.ReplyId);
            root.put("Content", mEdComment.getText().toString());
            root.put("Score", mRbEdit.getRating());
            root.put("ParentId", 0);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return RequestBody.create(MediaType.parse("application/json"), root.toString());
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus) {

            int isRating = getIntent().getIntExtra(IS_FROM_RATING, 0);
            if (isRating == 0 && mReply == null) {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {

                    public void run() {
                        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }, 200); // 秒后自动弹出
//                mEdComment.requestFocus();
//                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//            imm.showSoftInput(mEdComment,InputMethodManager.SHOW_FORCED);
//                InputMethodManager inputMethodManager=
//                        (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//                inputMethodManager.toggleSoftInput(
//                        InputMethodManager.SHOW_IMPLICIT,
//                        InputMethodManager.HIDE_IMPLICIT_ONLY);
            }
        }
    }

}
